import { loadDicts, loadDictList } from '@/api/dict'
import { Module } from 'vuex'

export const dictKeyList = new Set(['sys_user_sex', 'audit_status'])

const dict: Module<Store.DictState, Store.RootState> = {
  namespaced: true, // 必须要开放
  state: {},
  mutations: {
    SET_DICT: (state, { key, data }) => {
      state[key] = data
    }
  },
  actions: {
    // 获取全部字典
    async setDictList({ commit }) {
      try {
        const { data } = await loadDictList([...dictKeyList])
        Object.entries(data).forEach(([key, dict]) => {
          commit('SET_DICT', {
            key: key,
            data: dict
          })
        })
      } catch (error) {
        console.error(`获取字典 error =>`, error)
      }
    },
    // 设置单字典
    async setDict({ commit }, key) {
      try {
        const { data } = await loadDicts(key)
        commit('SET_DICT', {
          key: key,
          data
        })
      } catch (error) {
        console.error(`获取字典 ${key} error =>`, error)
      }
    },
    // 获取全部字典
    async setDictAll({ dispatch }) {
      try {
        await Promise.all([...dictKeyList].map(async key => await dispatch('setDict', key)))
      } catch (error) {
        console.error(`获取字典 All error =>`, error)
      }
    }
  }
}

dictKeyList.forEach(key => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  dict.state[key] = []
})

export default dict
